package cn.kgc.shiro01;

import cn.kgc.shiro01.shiro.CustomerRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;

import java.util.Arrays;
import java.util.List;

/**
 * @Author: 课工场
 * @Version: v1.0  2023/3/31
 * @Description:
 */
public class TestShiro02 {

    public static void main(String[] args) {

        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        CustomerRealm realm = new CustomerRealm();
        // 给域对象 设置凭证匹配器  新的密码比较规则
        HashedCredentialsMatcher  hashedCredentialsMatcher =  new HashedCredentialsMatcher("MD5");
        // 设置散列的次数
        hashedCredentialsMatcher.setHashIterations(20);

        realm.setCredentialsMatcher(hashedCredentialsMatcher);

        defaultSecurityManager.setRealm(realm);
        SecurityUtils.setSecurityManager(defaultSecurityManager);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken("tom", "123456");
        // 认证操作
        subject.login(usernamePasswordToken);

        // 授权  user/delete   admin角色  编程式  注解方式
        boolean b = subject.hasRole("admin");
        System.out.println(" has role admin = " + b);

        List<String> roles = Arrays.asList("admin", "super");
        boolean b1 = subject.hasAllRoles(roles);
        System.out.println(" has all role admin&super  = " + b1);


        // 基于权限字符串的授权   user:delete  user:update  teacher:delete
        boolean permitted = subject.isPermitted("user:delete");
        System.out.println(" user:delete permitted = " + permitted);


        permitted = subject.isPermitted("user:update");
        System.out.println(" user:update permitted = " + permitted);
        
    }

}
